import { UseOptions } from '../../interface/cmd'
import { SwaggerDocTnd, UsePaths } from '../../interface/swagger'
import { getFileNameByTags, getRequestNameByPath, removeDuplicate } from '../../utils'
import {
  WorkeMod,
  apiName,
  getJsApiLine,
  getProperties,
  getTsApiLine,
  handleNestVo,
  supplementArr,
  writeFile
} from './common'

export default function generateFileTnd(
  file: SwaggerDocTnd,
  option: UseOptions,
  paths: UsePaths[]
) {
  const { fileLine, defineLine, useFileName } = generateSingleTagsTnd(
    file,
    paths,
    option.t,
    option.js
  )
  const _fileLine =
    `import ${apiName(
      useFileName
    )}  from './${useFileName}.d' \nimport request from './request'\n\n` + fileLine
  return writeFile(option.path, useFileName, _fileLine, defineLine, option.js)
}

function generateSingleTagsTnd(
  file: SwaggerDocTnd,
  paths: UsePaths[],
  tagName: string,
  isJs: boolean = false
) {
  const useFileName = getFileNameByTags(tagName)
  const tag = paths.filter((item) => item.tags === tagName)
  let fileLine = ''
  if (isJs) {
    tag.forEach((item) => {
      fileLine += getJsApiLine(useFileName, item)
    })
  } else {
    tag.forEach((item) => {
      fileLine += getTsApiLine(useFileName, item)
    })
  }
  const defineLine = getSingleDefineLine(useFileName, paths, file)
  return {
    fileLine,
    defineLine,
    useFileName
  }
}

function getSingleDefineLine(useFileName: string, paths: UsePaths[], file: SwaggerDocTnd) {
  let defineTags = paths.map((item) => {
    return item.params && item.params!.indexOf('{') < 0 ? item.params : undefined
  })
  const perfix = `export namespace ${apiName(useFileName)}{\nnamespace ${useFileName}{\n`
  let defineLine = ''
  let responeTags = paths.map((item) => {
    return item.response && item.response!.indexOf('{') < 0
      ? item.response.replace(/\[\]/g, '')
      : undefined
  })
  defineTags = [...defineTags, ...responeTags]
  // 去重
  defineTags = removeDuplicate(defineTags)
  defineTags = defineTags.filter((item) => item !== undefined)
  defineTags.forEach((defineName, index) => {
    if (defineName) {
      const define = getProperties(file.components.schemas, defineName)
      defineLine += define + '\n'
    }
  })
  const supplementLine = handleNestVo(file.components.schemas)
  return perfix + defineLine + '\n}\n}'
}
